#include "AnimatedSprite.hpp"
#include "DrawableDataPool.hpp"
#include "Drawable.hpp"
#include "AnimationData.hpp"

namespace se{
namespace Graphics{

boost::function<void(sf::RenderTarget& r,Drawable& d)>
	AnimatedSpritePOD::renderFunction = render;

AnimatedSpritePOD::AnimatedSpritePOD(AnimationData *d,Time_t t):
	animation(d),
	currentTime(t){
}

void AnimatedSpritePOD::render(sf::RenderTarget& r,Drawable& d){
	AnimatedSpritePOD& data = boost::get<AnimatedSpritePOD>(d.data);
	AnimationData *a = data.animation;
	sf::Sprite sprite(a->GetSourceImage(),a->GetSubrectFromTime(data.currentTime));
	sprite.setOrigin(data.getOrigin());
	sprite.setPosition(data.getPosition());
	sprite.setRotation(data.getRotation());
	sprite.setScale(data.getScale());
	r.draw(sprite);
}


/********************************************//**
 * Creates an empty AnimatedSprite.
 *
 * Mainly for debug use, or without loading from a
 * DrawableDatapool.
 *
 * Not recommended for normal use, mainly because there is no way to
 * use it afterwards. To study...
 ***********************************************/
AnimatedSprite::AnimatedSprite():
	AnimatedSpritePOD(NULL,0),
	Layer(0),
	m_timeRef(NULL),
	m_dataPool(NULL),
	m_timeStarted(0){
	m_timeStarted = System::time->Game_ms();
}
/********************************************//**
 * Creates an empty AnimatedSprite, and link it to a DrawableDataPool.
 * 
 * 
 ***********************************************/
AnimatedSprite::AnimatedSprite(DrawableDataPool &pool) :
	AnimatedSpritePOD(NULL,0),
	Layer(0),
	m_timeRef(NULL),
	m_dataPool(&pool),
	m_timeStarted(0){
}

AnimatedSprite::~AnimatedSprite(){
	
}

void AnimatedSprite::SetAnim(const std::string& animName){
	if(!m_dataPool){
		return;
	}
	animation = m_dataPool->Get(animName);
	m_timeStarted = getTime();
}

/********************************************//**
 * \brief Updates the sprite for display.
 *
 * Set the correct subrect for display.
 *
 ***********************************************/
void AnimatedSprite::Update(){
	currentTime = getTime()-m_timeStarted;
}

Time_t AnimatedSprite::getTime(){
	return m_timeRef ? m_timeRef->Time_ms() : System::time->Game_ms();
}

void AnimatedSprite::SetTimeRef(System::Chrono& c){
	currentTime = getTime();
}

}}//</namespace se::Graphics>

